package com.example.deepai.controller;

import com.example.deepai.model.ChatMessage;
import com.example.deepai.model.ChatSession;  // 添加这行
import com.example.deepai.repository.ChatMessageRepository;
import com.example.deepai.repository.ChatSessionRepository;  // 添加这行
import com.example.deepai.service.DeepSeekService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;  // 添加这行
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.HashMap;
@Slf4j
@RestController
@RequestMapping("/api/chat")
@RequiredArgsConstructor
public class ChatController {

    private final ChatMessageRepository chatMessageRepository;
    private final ChatSessionRepository chatSessionRepository;
    private final DeepSeekService deepSeekService;

    @PostMapping("/sessions")
    public ResponseEntity<ChatSession> createSession() {
        ChatSession session = new ChatSession();
        session.setSessionId(UUID.randomUUID().toString());
        session.setTitle("新对话");
        return ResponseEntity.ok(chatSessionRepository.save(session));
    }

    @GetMapping("/sessions")
    public ResponseEntity<List<ChatSession>> getSessions() {
        return ResponseEntity.ok(chatSessionRepository.findAllByOrderByLastMessageTimeDesc());
    }

    @PostMapping("/send")
    public ResponseEntity<?> sendMessage(@RequestBody Map<String, String> request) {
        String content = request.get("content");
        
        log.info("收到用户消息: content={}", content);

        if (content == null || content.trim().isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of("error", "消息内容不能为空"));
        }

        try {
            // 先创建或获取会话
            final String initialSessionId = request.get("sessionId");
            final ChatSession session;
            final String finalSessionId;  // 改名为 finalSessionId
            
            if (initialSessionId == null || initialSessionId.trim().isEmpty()) {
                // 如果没有sessionId，创建新会话
                session = new ChatSession();
                session.setSessionId(UUID.randomUUID().toString());
                session.setTitle(content.substring(0, Math.min(20, content.length())));
                chatSessionRepository.save(session);
                finalSessionId = session.getSessionId();
            } else {
                finalSessionId = initialSessionId;
                // 如果有sessionId，获取现有会话或创建新会话
                session = chatSessionRepository.findById(finalSessionId)
                    .orElseGet(() -> {
                        ChatSession newSession = new ChatSession();
                        newSession.setSessionId(finalSessionId);
                        newSession.setTitle(content.substring(0, Math.min(20, content.length())));
                        return chatSessionRepository.save(newSession);
                    });
            }

            // 更新会话的最后消息时间
            session.setLastMessageTime(LocalDateTime.now());
            chatSessionRepository.save(session);

            // 创建用户消息
            ChatMessage userMessage = new ChatMessage(finalSessionId, "user", content);
            chatMessageRepository.save(userMessage);
            log.info("用户消息已保存: id={}", userMessage.getId());

            // 获取历史消息
            List<ChatMessage> history = chatMessageRepository.findBySessionIdOrderByTimestampAsc(finalSessionId);
            log.info("获取到历史消息: count={}", history.size());

            // 调用AI获取回复
            log.info("开始调用DeepSeek API...");
            String aiResponse = deepSeekService.getCompletion(content, history);
            log.info("DeepSeek API返回响应: {}", aiResponse.substring(0, Math.min(100, aiResponse.length())) + (aiResponse.length() > 100 ? "..." : ""));

            // 创建AI回复消息
            ChatMessage aiMessage = new ChatMessage(finalSessionId, "assistant", aiResponse);
            chatMessageRepository.save(aiMessage);
            log.info("AI回复已保存: id={}", aiMessage.getId());

            // 构建返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("sessionId", finalSessionId);
            response.put("message", aiMessage);
            
            return ResponseEntity.ok(response);

        } catch (IOException e) {
            log.error("处理消息失败", e);
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.internalServerError().body(errorResponse);
        }
    }

    @GetMapping("/history/{sessionId}")
    public ResponseEntity<List<ChatMessage>> getHistory(@PathVariable String sessionId) {
        List<ChatMessage> messages = chatMessageRepository.findBySessionIdOrderByTimestampAsc(sessionId);
        return ResponseEntity.ok(messages);
    }

    @DeleteMapping("/sessions/{sessionId}")
    public ResponseEntity<?> deleteSession(@PathVariable String sessionId) {
        try {
            // 先检查会话是否存在
            if (!chatSessionRepository.existsById(sessionId)) {
                return ResponseEntity.notFound().build();
            }
            
            // 删除该会话下的所有消息
            chatMessageRepository.deleteBySessionId(sessionId);
            
            // 删除会话本身
            chatSessionRepository.deleteById(sessionId);
            
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            log.error("删除会话失败: sessionId={}", sessionId, e);
            return ResponseEntity.internalServerError()
                .body(Map.of("error", "删除会话失败: " + e.getMessage()));
        }
    }

    // 删除 sendMessageStream 方法
}